package com.sj.uabrowser.app;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.WindowManager;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class Util {

    private static Context context;

    public static void init(Context c) {
        context = c;
    }

    public static void showToastShort(String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    public static void showToastLong(String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
    }

    public static int transPX(float dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                context.getResources().getDisplayMetrics());
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue
     *            （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    public static DisplayMetrics getDisplayMetrics() {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics out = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(out);
        return out;
    }

    public static String getSdCardPath() {
        return Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
    }

    public static String getDeviceDevice() {
//        return Build.DEVICE;
        return Build.MANUFACTURER;
    }

    public static String getDeviceModel() {
        return Build.MODEL;
    }

    public static String getChannelName() {
//        return AnalyticsConfig.getChannel(context);
        try {
            PackageManager pm = context.getPackageManager();
            ApplicationInfo appInfo = pm.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            return appInfo.metaData.getString("UMENG_CHANNEL");
        } catch (PackageManager.NameNotFoundException ignored) {
        }
        return "";
    }

    public static String formatDouble(double num) {
        java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
        return df.format(num);
    }

    public static String getFileSize(long contentLength) {
        double size = contentLength / (1024.0 * 1024);
        if (size > 0) {
            return formatDouble(size) + "M";
        } else if ((size = contentLength / 1024.0) > 0) {
            return formatDouble(size) + "K";
        }
        return size + "B";
    }

    public static String getVersionName() {
        PackageManager manager = context.getPackageManager();
        String name = null;
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            name = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return name;
    }

    public static String getSerialNum() {
        return Build.SERIAL;
    }

    public static String getManufactor() {
        return Build.MANUFACTURER;
    }


    public static String getReleaseVersion() {
        return Build.VERSION.RELEASE;
    }

    public static int getDeviceSDK() {
        return Build.VERSION.SDK_INT;
    }

    public static String getLang() {
        return Locale.getDefault().getCountry();
    }

    public static String getChip() {//芯片类型
        return Build.CPU_ABI;
    }

    public static String getRAMInfo() {
        long totalSize = 0;
        long availableSize = 0;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo info = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(info);
        totalSize = info.totalMem;
        availableSize = info.availMem;
        return /*"总共/可用："+*/ Formatter.formatFileSize(context, availableSize) + "/"
                + Formatter.formatFileSize(context, totalSize);
    }

    public static String getEquipmentCode() {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String deviceId = tm.getDeviceId();
        if (deviceId == null) {
            return "unkown";
        }
        return deviceId;
    }

//    public static String getApiVersion() {
//        return "v1";
//    }

    /**
     * 启动到应用商店app详情界面
     *
     * @param appPkg    目标App的包名
     * @param marketPkg 应用商店包名 ,如果为""则由系统弹出应用商店列表供用户选择,否则调转到目标市场的应用详情界面，某些应用商店可能会失败
     */
    public static void launchAppDetail(String appPkg, String marketPkg) {
        try {
            if (TextUtils.isEmpty(appPkg)) return;

            Uri uri = Uri.parse("market://details?id=" + appPkg);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            if (!TextUtils.isEmpty(marketPkg)) {
                intent.setPackage(marketPkg);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 判断市场是否存在的方法
    public static boolean isAvilible(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        List<String> pName = new ArrayList<String>();// 用于存储所有已安装程序的包名
// 从pinfo中将包名字逐一取出，压入pName list中
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                pName.add(pn);
            }
        }
        return pName.contains(packageName);// 判断pName中是否有目标程序的包名，有TRUE，没有FALSE
    }

    public static String getPackageNameByChannel(String channelName) {
        switch (channelName) {
//            case "":return "com.android.vending";//	Google Play
            case "qq":
                return "com.tencent.android.qqdownloader";//	应用宝
            case "c360":
                return "com.qihoo.appstore";//	360手机助手
            case "baidu":
                return "com.baidu.appsearch";//	百度手机助
            case "mi":
                return "com.xiaomi.market";//	小米应用商店
            case "wandoujia":
                return "com.wandoujia.phoenix2";//	豌豆荚
            case "huawei":
                return "com.huawei.appmarket";//	华为应用市场
//            case "":return "com.taobao.appcenter";//	淘宝手机助手
//            case "":return "com.hiapk.marketpho";//	安卓市场
            case "anzhi":
                return "cn.goapk.market";//	安智市场
        }

        return "";
    }

    /**
     * 获取当前进程名
     */
    public static String getCurrentProcessName() {
        int pid = android.os.Process.myPid();
        String processName = "";
        ActivityManager manager = (ActivityManager) context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo process : manager.getRunningAppProcesses()) {
            if (process.pid == pid) {
                processName = process.processName;
            }
        }
        return processName;
    }

//    public static Bitmap getShareBitmap() {
//        return BitmapFactory.decodeResource(context.getResources(), R.mipmap.zhijiao_fengxiang);//ic_launcher2  //share_logo
//    }

    public static boolean orMIUI() {
        String manufacturer = Build.MANUFACTURER;
        if ("xiaomi".equalsIgnoreCase(manufacturer)) {
            return true;
        }
        return false;

    }

    public static String getNightCode(int resId){
        InputStream is = context.getResources().openRawResource(resId);
        byte[] buffer = new byte[0];
        try {
            buffer = new byte[is.available()];
            is.read(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Base64.encodeToString(buffer, Base64.NO_WRAP);
    }

    public static Bitmap getBitmap(int id) {
        return BitmapFactory.decodeResource(context.getResources(), id);
    }

    public static int getResourceId(String type, String name) {
        return context.getResources().getIdentifier(name, type, context.getPackageName());
    }

    public static Bitmap getBitmap(String name){
        return BitmapFactory.decodeResource(context.getResources(), context.getResources().getIdentifier(name, "mipmap", context.getPackageName()));
    }

    public static String getTimeDuration2(String time){
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日");
            String start = sdf.format(new Date(Long.parseLong(time) * 1000));
            String end = sdf.format(new Date((Long.parseLong(time)+14*24*60*60) * 1000));
            return start + "~" + end;
        }catch (Exception e){
            return "";
        }
    }

    public static String getTimeDuration(String time){
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日");
            String start = sdf.format(new Date(Long.parseLong(time) * 1000));
            String end = sdf.format(new Date((Long.parseLong(time)+13*24*60*60) * 1000));
            return start + "~" + end;
        }catch (Exception e){
            return "";
        }
    }

    public static String getWeekDay(String time){
        Date date = new Date(Long.parseLong(time)*1000);
        String month_day = getDay1(time);
        String week = getDamaiDay(date);
        return month_day+" "+week;
    }

    public static String getDay1(String time){
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd");
        return sdf.format(new Date(Long.parseLong(time)*1000));
    }

    public static String getDay0(int i,String time){
        if(i==0){
            return "今天";
        }else if(i==1){
            return "明天";
        }else{
            Date date = new Date(Long.parseLong(time)*1000);
            String week = getDamaiDay(date);
            return week;
        }
    }

    private static String getDamaiDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        switch (calendar.get(Calendar.DAY_OF_WEEK)) {
            case Calendar.MONDAY:
                return "周一";
            case Calendar.TUESDAY:
                return "周二";
            case Calendar.WEDNESDAY:
                return "周三";
            case Calendar.THURSDAY:
                return "周四";
            case Calendar.FRIDAY:
                return "周五";
            case Calendar.SATURDAY:
                return "周六";
            case Calendar.SUNDAY:
                return "周日";
            default:
                return "";
        }
    }


    public static Bitmap scaleBitmap(Bitmap src,float scale){
        Matrix matrix = new Matrix();
        matrix.setScale(scale,scale);
        return Bitmap.createBitmap(src,0,0,src.getWidth(),src.getHeight(),matrix,false);

    }

    /**
     * 获取apk包的信息：版本号，名称，图标等
     * @param absPath apk包的绝对路径
     * @param context
     */
    public static Drawable apkInfo(String absPath,Context context) {

        PackageManager pm = context.getPackageManager();
        PackageInfo pkgInfo = pm.getPackageArchiveInfo(absPath,PackageManager.GET_ACTIVITIES);
        if (pkgInfo != null) {
            ApplicationInfo appInfo = pkgInfo.applicationInfo;
            /* 必须加这两句，不然下面icon获取是default icon而不是应用包的icon */
            appInfo.sourceDir = absPath;
            appInfo.publicSourceDir = absPath;
            String appName = pm.getApplicationLabel(appInfo).toString();// 得到应用名
            String packageName = appInfo.packageName; // 得到包名
            String version = pkgInfo.versionName; // 得到版本信息
            /* icon1和icon2其实是一样的 */
            Drawable icon1 = pm.getApplicationIcon(appInfo);// 得到图标信息
            Drawable icon2 = appInfo.loadIcon(pm);
            return icon2;
//            String pkgInfoStr = String.format("PackageName:%s, Vesion: %s, AppName: %s", packageName, version, appName);
//            Log.i(TAG, String.format("PkgInfo: %s", pkgInfoStr));
        }else{
            return null;
        }
    }

}
